// 导入koa，和koa 1.x不同，在koa2中，我们导入的是一个class，因此用大写的Koa表示:
const Koa = require('koa');
const Router = require('koa-router');
const cors = require('koa2-cors');
const path = require('path');
const KoaStatic = require('koa-static');
const koaBody = require('koa-body'); //解析上传文件的插件
const fs = require('fs');
const baseUrl = 'http://localhost:3333';
const utils = require('./utils')



// 创建一个Koa对象表示web app本身:
const app = new Koa();
app.use(cors());
// 使用koa-static处理静态资源
app.use(KoaStatic('./'));

app.use(koaBody({
  uploadDir: path.join(__dirname, 'upload/'), // 设置文件上传目录
  multipart: true,
  formidable: {
    maxFileSize: 2000 * 1024 * 1024    // 设置上传文件大小最大限制，默认2M
  }
}))

// 上传文件处理
function uploadFn (ctx, destPath) {
  return new Promise((resolve, reject) => {
    const file = ctx.request.files.file
    const reader = fs.createReadStream(file.path)
    let filePath = path.join(__dirname, 'upload/' + `/${file.name}`)
    const upStream = fs.createWriteStream(filePath)
    reader.pipe(upStream)
    resolve(file.name)
  })
}

let testApi = new Router();

// 上传图片
testApi.post('/testApi/uploadImg', async ctx => {
  await uploadFn(ctx).then((name) => {
    ctx.body = {
      code: 200,
      data: baseUrl + '/upload/' + name,
      msg: '文件上传成功'
    }
  })
});

// 上传大文件
testApi.post('/testApi/uploadBigFile', async ctx => {
  let type = ctx.request.query.type;
  let md5Val = ctx.request.query.md5Val;
  let total = ctx.request.query.total;
  let current = ctx.request.query.current;
  let ext = ctx.request.query.ext;
  if (!type) {
    return ctx.body = {
      code: 101,
      msg: '上传类型不能为空！'
    }
  }
  if (!md5Val) {
    return ctx.body = {
      code: 101,
      msg: '文件md5值不能为空！'
    }
  }
  if (!total) {
    return ctx.body = {
      code: 101,
      msg: '文件切片数量不能为空！'
    }
  }





  // 合并文件
  if (type == 'merge') {
    if (!ext) {
      ctx.body = {
        code: 101,
        msg: '文件名后缀不能为空'
      }
    }
    let oldPath = path.join(__dirname, `upload/bigFile/${md5Val}`);
    let newPath = path.join(__dirname, `upload/resultBigFile/${md5Val}${ext}`);
    let data = await utils.mergeFile(oldPath, newPath);
    if (data.code == 200) {
      ctx.body = {
        code: 200,
        data: `${baseUrl}/upload/resultBigFile/${md5Val}${ext}`,
        msg: '文件合并成功！'
      }
    } else {
      ctx.body = {
        code: 101,
        msg: '文件合并失败！'
      }
    }
  }

  // 检查文件是否存在
  if (type == 'check') {
    // 秒传_判断文件夹中是否存在相同得到md5文件名称
    if (fs.existsSync(path.join(__dirname, `upload/resultBigFile/${md5Val}${ext}`))) {
      return ctx.body = {
        code: 220,
        data: `${baseUrl}/upload/resultBigFile/${md5Val}${ext}`,
        msg: '上传成功'
      }
    }
    let curFileDir = path.join(__dirname, `upload/bigFile/${md5Val}`)
    utils.checkDirExist(curFileDir)
    console.log("ssssssss")
    let curFileArray = await fs.readdirSync(curFileDir)

    ctx.body = {
      code: 221,
      data: curFileArray.length,
      msg: '获取成功！'
    }

  }

  // 上传文件
  if (type == 'upload') {
    // 正常分片上传
    let dir = path.join(__dirname, `upload/bigFile/${md5Val}`);
    utils.checkDirExist(dir)
    const file = ctx.request.files.bigFile
    const reader = fs.createReadStream(file.path)
    let filePath = path.join(__dirname, `upload/bigFile/${md5Val}/${md5Val}_${current}`)
    const upStream = fs.createWriteStream(filePath)
    reader.pipe(upStream)
    ctx.body = {
      code: 200,
      msg: '获取成功！'
    }
  }
});




app.use(testApi.routes());


// 在端口3333监听:
app.listen(3333);
console.log(`服务器已启动  http://localhost:3333`)